import React from 'react';
import { Breadcrumb, Icon, Table, Button, Modal, Col, Input, Carousel, message, Row, Form, Checkbox, Menu, Dropdown, Select } from 'antd';
import './SeoLabel.less';
import $ from 'jquery';
import Config from '../../common/config';

const config = new Config();
const token = sessionStorage.getItem('token');
const FormItem = Form.Item;
const confirm = Modal.confirm;


class SeoLabel extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            seoHome: [],//首页标签
            seoCategory: [],//分类标签
            seoDetail: [],//详情标签
            addUpdate: {
                id: "",//主键id
                seoTagTypeId: "",//SEO标签类型ID
                seoType: "",//SEO类型（1:首页，2:分类, 3:商品详情）
                tagContent: "",//标签内容
                categoryId: "",//分类id
            },
            seoCategoriesArr: [],//获取分类列表
            seoTagTypeArr: [],//SEO标签类型数组
            visible: false,
            selectType: "请选择",
            selectCategories: "请选择",
            ismodeltitle:"新增",
        }
    }
    componentDidMount() {
        this.getSeolabelList();
        this.getseoTypeLIst();
        this.getcategories()
    }
    //获取标签列表
     getSeolabelList() {
        $.ajax({
            url: `${config.JuseHomepage}/seoSetting/list`,
            type: "get",
            headers: { Authorization: 'Bearer ' + token, },
            success:function(res){
                if (res.code === 200) {
                    let seoHome = [], seoCategory = [], seoDetail = [];
                    res.data.map(item => {
                        item.data = item.data.map(itemName => {
                            itemName.showseoType = item.seoType;
                            return itemName
                        });
                        switch (item.seoType) {
                            case 1:
                                seoHome = item.data;
                                break;
                            case 2:
                                seoCategory = item.data;
                                break;
                            case 3:
                                seoDetail = item.data;
                                break;
                        }
                    });
                    this.setState({ seoHome, seoCategory, seoDetail });
                }
            }.bind(this)
        });

    }
    //获取标签列表
     getseoTypeLIst() {
        $.ajax({
            url: `${config.JuseHomepage}/seoTagType/list`,
            type: "get",
            headers: { Authorization: 'Bearer ' + token },
            success:function(res){
                (res.code == 200) && (this.setState({ seoTagTypeArr: res.data.rows, }));
            }.bind(this)
        });

    }
    //获取分类列表
     getcategories() {
       $.ajax({
            url: `${config.JuseHomepage}/seoSetting/categories`,
            type: "get",
            headers: { Authorization: 'Bearer ' + token },
           success:function(res){
               res.code == 200 && this.setState({ seoCategoriesArr: res.data, });
           }.bind(this)
        });

    }
    //新增Or修改
    addFloorshowModal(obj) {
        let addUpdate = this.state.addUpdate;
        addUpdate.seoType = obj.seoType;
        if (obj.id) {//说明是更新数据
            let seoArr = obj.record;
            addUpdate.tagContent = seoArr.tagContent;
            addUpdate.id = seoArr.id;
            addUpdate.seoTagTypeId = seoArr.seoTagTypeId;
            if (obj.seoType == 2) {//说明是分类
                addUpdate.categoryId = seoArr.categories_show.categoryId;
                this.setState({
                    selectCategories: seoArr.categories_show.categoryName,

                });
            }
            this.setState({
                selectType: seoArr.seo_tag_type.tagName,
                addUpdate,
                ismodeltitle:"修改",
            });
        } else {//说明是
            this.setState({
                selectCategories: "请选择",
                selectType: "请选择",
                ismodeltitle:"新增",
            });
        }
        this.setState({
            visible: !this.state.visible,
            addUpdate: addUpdate,
        })
    }
    //删除
     deleteKeyword(obj) {
        console.log(obj);
        $.ajax({
            url: `${config.JuseHomepage}/seoSetting/delete`,
            type: "post",
            data: { id: obj.id },
            headers: { Authorization: 'Bearer ' + token },
            success:function(res){
                if (res.code == 200) {
                    this.getSeolabelList();
                } else {
                    message.error(res.mes, 2);
                }
            }.bind(this)
        });

    }
     handleOk() {
        let addUpdate, url;
        addUpdate = this.state.addUpdate;
        if (addUpdate.id) {//说明无有值   添加
            url = `${config.JuseHomepage}/seoSetting/update`;
        } else {//说明有值   修改
            delete addUpdate.id;
            url = `${config.JuseHomepage}/seoSetting/add`;//
        }
        if(addUpdate.seoType==2){
            if (!addUpdate.categoryId) {//如果不存在
                message.error(`请选择分类`, 2);
                return;
            }
        }
        if (addUpdate.categoryId) {

        } else {
            delete addUpdate.categoryId;
        }
       $.ajax({
            url: url,
            type: "post",
            data: addUpdate,
            headers: { Authorization: 'Bearer ' + token },
             success:function(res){
                 if (res.code == 200) {
                     this.getSeolabelList();
                     this.setState({
                         visible: !this.state.visible,
                         addUpdate: {
                             id: "",//主键id
                             seoTagTypeId: "",//SEO标签类型ID
                             seoType: "",//SEO类型（1:首页，2:分类, 3:商品详情）
                             tagContent: "",//标签内容
                             categoryId: "",//分类id
                         },
                     })
                 } else {
                     message.error(res.mes, 2);
                 }
             }.bind(this),
        });



    }
    handleCancel() {
        this.setState({
            visible: !this.state.visible,
            addUpdate: {
                id: "",//主键id
                seoTagTypeId: "",//SEO标签类型ID
                seoType: "",//SEO类型（1:首页，2:分类, 3:商品详情）
                tagContent: "",//标签内容
                categoryId: "",//分类id
            },
        })
    }
    handleMenuClick(id) {
        let addUpdate = this.state.addUpdate;
        addUpdate.seoTagTypeId = id;
        this.setState({ addUpdate: addUpdate })
    }
    InputChange(e) {
        let addUpdate = this.state.addUpdate;
        addUpdate.tagContent = e.target.value;
        this.setState({ addUpdate: addUpdate })
    }
    //分类事件
    seoCategoriesArrClick(id) {
        let addUpdate = this.state.addUpdate;
        addUpdate.categoryId = id;
        this.setState({ addUpdate: addUpdate })
    }
    render() {
        const columns = [
            {
                title: '标签类型',
                dataIndex: 'seo_tag_type.tagName',
                width: '25%',
            },
            {
                title: '标签内容',
                dataIndex: 'tagContent',
                width: '50%',
                render: (text, record) => (
                    <a href={text} target='_blank'>{text}</a>
                )
            },
            {
                title: '操作',
                key: 'edit',
                width: '25%',
                render: (text, record) => (
                    <span>
                        <a href="javascript:void(0);" onClick={() => this.addFloorshowModal({ seoType: record.showseoType, id: record.id, record: record })} >编辑</a>&nbsp;&nbsp;&nbsp;&nbsp;
                        <a href="javascript:void(0);" onClick={() => this.deleteKeyword(record)}>删除</a>
                    </span>
                )
            }
        ];
        const columns2 = [
            {
                title: '标签类型',
                dataIndex: 'seo_tag_type.tagName',
                width: '25%',
            },
            {
                title: '标签内容',
                dataIndex: 'tagContent',
                width: '25%',
                render: (text, record) => (
                    <a href={text} target='_blank'>{text}</a>
                )
            },
            {
                title: '标签分类',
                dataIndex: 'categories_show.categoryName',
                width: '25%',
                render: (text, record) => (
                    <a href={text} target='_blank'>{text}</a>
                )
            },
            {
                title: '操作',
                key: 'edit',
                width: '25%',
                render: (text, record) => (
                    <span>
                        <a href="javascript:void(0);" onClick={() => this.addFloorshowModal({ seoType: record.showseoType, id: record.id, record: record })} >编辑</a>&nbsp;&nbsp;&nbsp;&nbsp;
                            <a href="javascript:void(0);" onClick={() => this.deleteKeyword(record)}>删除</a>
                    </span>
                )
            }
        ];
        const menu = (
            this.state.seoTagTypeArr.map((item, i) => (
                <Option value={item.id} key={item.id}>{item.tagName}</Option>
            ))
        );
        const seoCategoriesArr = (
            this.state.seoCategoriesArr.map((item, i) => (
                <Option value={item.categoryId} key={item.categoryId}>{item.categoryName}</Option>
            ))
        )
        return (
            <div className='goods-label'>
                <div className='goods-label-cont clearfix'>
                    <div className='goods-label-cont-nav clearfix'>
                        <Breadcrumb separator=">">
                            <Breadcrumb.Item>首页管理</Breadcrumb.Item>
                            <Breadcrumb.Item>seo标签</Breadcrumb.Item>
                        </Breadcrumb>
                    </div>
                    <div className='allgoods-table clearfix' style={{ marginTop: 10 }}>
                        <h1 style={{ fontSize: '16px', marginBottom: '10px' }}>首页标签设置</h1>
                        <Table
                            className="floor-table"
                            rowKey="id"
                            columns={columns}
                            dataSource={this.state.seoHome}
                            pagination={false}
                            bordered
                        />
                        <div className='goods-label-tabletr'>
                            <Button className='goods-label-table-app' width={160} icon="plus" onClick={() => this.addFloorshowModal({ seoType: 1 })}>新增</Button>
                        </div>
                    </div>

                    <div className='allgoods-table clearfix' style={{ marginTop: 40 }}>
                        <h1 style={{ fontSize: '16px', marginBottom: '10px' }}>分类标签设置</h1>
                        <Table
                            className="floor-table"
                            rowKey="id"
                            columns={columns2}
                            dataSource={this.state.seoCategory}
                            pagination={false}
                            bordered
                        />
                        <div className='goods-label-tabletr'>
                            <Button className='goods-label-table-app' width={160} icon="plus" onClick={() => this.addFloorshowModal({ seoType: 2 })}>新增</Button>
                        </div>
                    </div>

                    <div className='allgoods-table clearfix' style={{ marginTop: 40 }}>
                        <h1 style={{ fontSize: '16px', marginBottom: '10px' }}>详情标签设置</h1>
                        <Table
                            className="floor-table"
                            rowKey="id"
                            columns={columns}
                            dataSource={this.state.seoDetail}
                            pagination={false}
                            bordered
                        />
                        <div className='goods-label-tabletr'>
                            <Button className='goods-label-table-app' width={160} icon="plus" onClick={() => this.addFloorshowModal({ seoType: 3 })}>新增</Button>
                        </div>
                    </div>
                </div>

                <Modal title={this.state.ismodeltitle} visible={this.state.visible}
                    onOk={this.handleOk.bind(this)}
                    onCancel={this.handleCancel.bind(this)}
                >
                    <div className='thrnt'>
                        {
                            this.state.visible ?
                                <Row>
                                    <Col span={6} style={{ textAlign:'right'}}>标题：</Col>
                                    <Col span={18}>
                                        <Select defaultValue={this.state.selectType}
                                            style={{ width: '100%' }}
                                            allowClear={this.state.visible}
                                            onChange={(e) => this.handleMenuClick(e)}>
                                            {menu}
                                        </Select>
                                    </Col>
                                </Row>
                                : null
                        }
                    </div>
                    <div className='thrnt'>
                        {
                            this.state.visible ?
                                <Row>
                                    <Col span={6} style={{ textAlign:'right'}}>标签内容：</Col>
                                    <Col span={18}>
                                        <Input
                                            placeholder="请输入标签内容"
                                            value={this.state.addUpdate.tagContent}
                                            onChange={(e) => this.InputChange(e)}
                                            ref={node => this.userNameInput = node}
                                        />
                                    </Col>
                                </Row>
                                : null
                        }

                    </div>
                    {

                        this.state.addUpdate.seoType == 2 && this.state.visible ?
                            <div className='thrnt'>
                                <Row>
                                    <Col span={6} style={{ textAlign:'right'}}>分类：</Col>
                                    <Col span={18}>
                                        <Select defaultValue={this.state.selectCategories}
                                            style={{ width: '100%' }}
                                            allowClear={this.state.visible}
                                            onChange={(e) => this.seoCategoriesArrClick(e)}>
                                            {seoCategoriesArr}
                                        </Select>
                                    </Col>
                                </Row>
                            </div>
                            :
                            null
                    }

                </Modal>


            </div>
        )
    }
}


export default SeoLabel;